package cn.livingCloud.controller.user;

import cn.livingCloud.dto.UserAccountFormDto;
import cn.livingCloud.dto.UserDto;
import cn.livingCloud.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by sujiantang on 2015/12/4.
 */
@Controller
@RequestMapping("/admin/user")
public class UserAccountFormController {
    @Qualifier("userAccountServiceImpl")
    @Autowired
    private UserAccountService accountService;

    @RequestMapping("/load.htm")
    public String loadUserAccount(UserAccountFormDto formDto, Model model) {
        formDto = accountService.loadUserAccount(formDto);
        model.addAttribute("formDto", formDto);
        return "user/edit_account";
    }

    @RequestMapping(value = "/update.htm", method = RequestMethod.POST)
    public String editUser(@ModelAttribute("formDto") @Valid UserAccountFormDto userAccountFormDto, BindingResult result, Model model) {
        if (result.hasErrors()) {
            return "user/edit_account";
        }
        String user = accountService.updateAccount(userAccountFormDto);
        model.addAttribute("user_id", user);
        model.addAttribute("edit", "success");
        return "redirect:/admin/user_account/list.htm";
    }

    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    public String deleteUser(String uuid, Model model) {
        accountService.deleteAccount(uuid);
        model.addAttribute("delete", "success");
        return "redirect:/admin/user_account/list.htm";
    }

    @RequestMapping("/search_list")
    @ResponseBody
    public List<UserDto> searchUserList(String key) {
        return accountService.searchUserList(key);
    }

}
